<template>
  <BasicModal
    v-bind="$attrs"
    @ok="handleSubmint"
    :minHeight="20"
    okText="提交"
    @register="register"
    :title="modalTitle"
    :loading="loading"
    @visible-change="handleVisibleChange"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm">
        <template #slotVariable="{ model, field }">
          <checkTag
            :value="model[field]"
            :isErroByVariable="isErroByVariable"
            @checkTag="handleCheckTag"
          />
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModal } from '/@/components/Modal';
  import { computed, nextTick, ref } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { checkName } from '/@/utils/index';
  import { addelement, editelement } from '/@/api/formula/index';
  import checkTag from '/@/components/selectTag/index.vue';

  const props = defineProps({
    info: {
      type: Object,
      default: () => {},
    },
    typeOptions: {
      type: Array,
      default: () => [],
    },
  });
  let isErroByVariable = ref<boolean>(false);

  let loading = ref(false);
  let modalTitle = computed(() => {
    return `${props.info.type === 'add' ? '新建' : '编辑'}产品成分`;
  });
  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'Name',
      component: 'Input',
      label: '名称：',
      helpMessage: '总长度为200字符，一个中文等于8个字符，数字/字母/英文下划线占1个字符',
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => checkName(value, '名称'),
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'DataType',
      component: 'Select',
      label: '数据类型：',
      colProps: {
        span: 24,
      },
      componentProps: {
        options: [],
        fieldNames: { label: 'Key', value: 'Value', key: 'Value' },
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => {
            if (['', null, undefined].indexOf(value) >= 0) {
              /* eslint-disable-next-line */
              return Promise.reject('请选择数据类型');
            }
            return Promise.resolve();
          },
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'TagFullName',
      component: 'Input',
      label: '关联变量：',
      slot: 'slotVariable',
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          message: '请选择关联变量',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'Unit',
      component: 'Input',
      label: '单位：',
      colProps: {
        span: 24,
      },
      // rules: [
      //   {
      //     required: true,
      //     message: '请输入单位',
      //     trigger: ['change', 'blur'],
      //   },
      // ],
    },
    {
      field: 'Description',
      component: 'InputTextArea',
      label: '备注：',
      colProps: {
        span: 24,
      },
    },
  ];

  const [
    registerForm,
    { validateFields, setFieldsValue, resetFields, clearValidate, updateSchema },
  ] = useForm({
    labelWidth: 120,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const { createMessage } = useMessage();
  const { t } = useI18n();
  const emit = defineEmits(['submitSuccess']);
  const [register] = useModal();

  function handleCheckTag(val) {
    let resList = val.val;
    setFieldsValue({
      TagFullName: Array.isArray(resList) && resList.length > 0 ? resList[0].FullName : '',
    });
    isErroByVariable.value = false;
  }
  async function handleSubmint() {
    try {
      let res = await validateFields();

      if (props.info.type === 'add') {
        await addelement([props.info.data.RecipeKey, res]);
      } else {
        await editelement([props.info.data.RecipeKey, props.info.data.ElementId, res]);
      }

      createMessage.success(t('layout.setting.operatingTitle'));
      emit('submitSuccess', {});
    } catch (error: any) {
      isErroByVariable.value = ['', null, undefined].indexOf(error.values.TagFullName) >= 0;
      console.log('not passing', error);
    }
  }

  async function handleVisibleChange(visible) {
    if (visible) {
      nextTick(async () => {
        if (props.info.type !== 'add') setFieldsValue(props.info.data);
        updateSchema({
          field: 'DataType',
          componentProps: {
            options: props.typeOptions,
          },
        });
        clearValidate();
      });
    } else {
      isErroByVariable.value = false;
      resetFields();
    }
  }
</script>

<style lang="less" scoped>
  .slot-select {
    width: 100%;
    height: 32px;
    padding: 0 11px;
    display: flex;
    position: relative;
    background-color: #fff;
    border: 1px solid #d9d9d9;
    border-radius: 2px;
    cursor: pointer;
  }

  .slot-select:hover {
    border: 1px solid #1e80ff;
  }

  .slot-select-con {
    margin-right: 18px;
    line-height: 30px;
    flex: 1;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    color: #000000d9;
    font-size: 14px;
  }

  .con-placeholder {
    color: #bfbfbf;
  }

  .icon-style {
    line-height: 30px;
    font-size: 11px;

    color: #bfbfbf;
  }

  .erro-style {
    border: 1px solid #ed6f6f !important;
  }

  .slot-select-diabled {
    background: #f5f5f5;
    cursor: not-allowed;

    .slot-select-con {
      color: rgba(0, 0, 0, 0.25);
    }
  }

  .slot-select-diabled:hover {
    border: 1px solid #d9d9d9;
  }
</style>
